const {user,Result} = require('../models');
const { gengerToken } = require('../tools');

async function addUser(ctx,next){
    let { username ,password } = ctx.request.body;
    if(!username || !password)return ctx.body = new Result(507,ctx.request.body,'参数缺失',false);
    let findUser = await user.findOne({where:{username}});
    if (findUser) {
        return ctx.body = new Result(511,null,'该用户已被注册',false);
    }
    await user.create({ username ,password }).then(success=>{
        console.log("添加用户成功");
        let {id} = success.dataValues;
        let token = gengerToken(id,username);
        user.update({token},{where:{id}});
        ctx.body = new Result(200,token,'Add user success',true);
    }).catch(err=>{
        console.log("添加用户失败",err);
        ctx.body = new Result(500,err,'Add user fail',false);
    })
}

async function login(ctx,next){
    let { username,password }  = ctx.request.body;
    if(!username || !password)return ctx.body = new Result(507,ctx.request.body,'参数缺失',false);
    let userinfo = await user.findOne({where:{ username,password }});
    if (!userinfo) {
        return ctx.body = new Result(506,userinfo,'账号或者密码错误',false);
    }
    let {id} = userinfo;
    let token = gengerToken(id,username);
    await user.update({token},{where:{id}});
    ctx.body = new Result(200,token,'登录成功',true);
}

async function getAll(ctx,next){
    let userArr = await user.findAll({
        attributes:['id','username']
    });
    if (userArr) {
        return ctx.body = new Result(200,userArr.map(e=>e.dataValues),'所有用户信息获取成功',true);
    }
    ctx.body = new Result(509,null,'所有用户信息获取失败',false);
}





module.exports = {
    'post /user':addUser,
    'post /login':login,
    'get /user':getAll
}